﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
using System.Xml;

namespace Raona.Silverlight
{

    public class TagItem
    {
        public string Key
        {
            get;
            set;
        }

        public string Value
        {
            get;
            set;
        }
    }	
    public class TagManager
    {

        #region Properties

        private static List<Dictionary<string, string>> _tagList = new List<Dictionary<string,string>>();

        public static event EventHandler<EventArgs> ConfigurationAvailable;

        public static List<Dictionary<string,string>> TagList
        {
            get
            {
                return _tagList;
            }
        
        }

        #endregion

        public static void LoadConfig()
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri("Tags.xml", UriKind.Relative));
        }

        public static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {

            if (e.Error != null)
            {
                throw e.Error;
            }

            // load the data
            XDocument config = XDocument.Parse(e.Result);

            var items = from x in config.Descendants("Items").Descendants("Item")
						select x;

            
			// add to collection
            if (items.Count() > 0)
            {
                foreach (var item in items)
                {
                 var tagDictionary = new Dictionary<string, string>();

                 var tags = from x in item.Descendants("Tag")
                              select new TagItem { Key = (string)x.Attribute("Key"), Value = x.Attribute("Value").Value };

											
					// add to collection
					if (tags.Count() > 0)
					{
						foreach (TagItem tag in tags)
						{
							tagDictionary[tag.Key] = tag.Value;
						}

						_tagList.Add(tagDictionary);	
					}
				}
			}


            // notify that its available
            if (ConfigurationAvailable != null)
                ConfigurationAvailable(null, new EventArgs());
        }

    }
}
